package com.da.javatest.util;

import com.da.javatest.enums.ErrorCodeEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;

/**
 * 参数校验工具类
 *
 * @author yizhi.cy
 * @Date 2017/9/29 下午8:00
 */
public class AssertUtils {

    /**
     * 不能为NULL
     *
     * @param obj
     */
    public static void notNull(Object obj) {
        if (obj == null) {
            throw new SrpException(ErrorCodeEnum.ILLEGAL_PARAMETER, "args must not be null");
        }
    }

    public static void notNull(Object... args) {
        if (args != null && args.length > 0) {
            for (Object obj : args) {
                if (obj == null) {
                    throw new SrpException(ErrorCodeEnum.ILLEGAL_PARAMETER,
                        "args must not be null");
                }
            }
        }
    }

    public static void notNull(Object obj, String msg) {
        if (obj == null) {
            throw new SrpException(ErrorCodeEnum.ILLEGAL_PARAMETER, msg);
        }
    }

    public static void notNullAndMsg(Object obj, String fieldName) {
        if (obj == null) {
            throw new SrpException(ErrorCodeEnum.ILLEGAL_PARAMETER, "[" + fieldName + "] 参数不能为空");
        }
        if (obj instanceof String) {
            if (StringUtils.isEmpty((String)obj)) {
                throw new SrpException(ErrorCodeEnum.ILLEGAL_PARAMETER,
                    "[" + fieldName + "] 参数不能为空");
            }
        }
    }

    public static void assertTrue(boolean state, String msg) {
        if (!state) {
            throw new SrpException(ErrorCodeEnum.ILLEGAL_PARAMETER, msg);
        }
    }

    public static void assertTrue(boolean state, ErrorCodeEnum errorCodeEnum) {
        if (!state) {
            throw new SrpException(errorCodeEnum, errorCodeEnum.getDesc());
        }
    }

    public static void assertNotEmpty(Collection collection, String msg) {
        if (collection == null || collection.isEmpty()) {
            throw new SrpException(ErrorCodeEnum.ILLEGAL_PARAMETER, msg);
        }
    }

    public static void assertEmpty(Collection collection, String msg) {
        if (collection != null && !collection.isEmpty()) {
            throw new SrpException(ErrorCodeEnum.ILLEGAL_PARAMETER, msg);
        }
    }

    public static void assertEquals(String a, String b) {
        if (!StringUtils.equals(a, b)) {
            throw new SrpException(ErrorCodeEnum.ILLEGAL_PARAMETER, "not equal");
        }
    }

}